<template>
    <div class="app-container">
      <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model.trim="queryParams.param.name" placeholder="请输入分类名称" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select style="width: 200px" v-model="queryParams.param.status" placeholder="请选择" clearable>
              <el-option v-for="dict in category_status" :key="dict.value" :label="dict.name"
                :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </searchBox>
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="info" plain @click="toggleExpandAll">展开/折叠</el-button>
  
      <el-table v-if="refreshTable" :data="tableData" row-key="id" :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" >
        <el-table-column label="ID"  prop="id"  />
        <el-table-column label="分类名称" prop="name">
          <template #default="scope">
            <el-space>
              <el-tooltip effect="dark" :content="scope.row.name">
                <el-text truncated style="width: 100px">{{
                  scope.row.name
                }}</el-text>
              </el-tooltip>
              <el-button link type="primary" @click="viewTranslate(scope.row)">查看翻译</el-button>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="seq" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch :width="58" v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt
              active-text="开启" inactive-text="关闭" :loading="switchStatus" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum" @pagination="handlePageChange">
      </Pagination>
  
      <!-- 添加或修改类别管理对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-col :span="14">
            <el-form-item label="上级ID" prop="fatherId">
              <el-tree-select v-model="form.fatherId" :data="categoryOptions" :props="treeProps" value-key="id"
                placeholder="请选择上级ID" check-strictly />
            </el-form-item>
          </el-col>
  
          <el-col :span="10">
            <el-form-item label="排序" prop="seq">
              <el-input type="number" v-model.trim="form.seq" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
  
          <!-- 一对多关系的内容 属性信息-->
          <el-col :span="24">
            <el-divider content-position="center">商品分类语言信息</el-divider>
            <MoreLanguage :newList="categoryDescriptionList" label="分类名称" @publicCheck="publicCheck"></MoreLanguage>
            <el-form-item label="状态" prop="status">
              <el-switch :width="58" class="demo" v-model="form.status" :active-value="1" :inactive-value="0"
                inline-prompt active-text="开启" inactive-text="关闭" />
            </el-form-item>
          </el-col>
          <!-- 一对多关系结束-->
        </el-form>
        <template v-slot:footer>
          <div class="public_box">
            <div>
              <el-button type="primary" @click="handleAddCategoryDescription">添加</el-button>
              <el-button type="danger" @click="handleDeleteCategoryDescription">删除</el-button>
            </div>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </template>
      </el-dialog>
      <Translation :dialogVisible="openViewTranslate" :languageList="translateData"
        @handleTranslationClose="handleTranslationClose"></Translation>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from "vue";
  const { proxy } = getCurrentInstance();
  const category_status = ref([
    {
      name: "开启",
      id: 1,
    },
    {
      name: "关闭",
      id: 0,
    },
  ]);
  const Judgment = ref(true); //设置true可以修改状态status的switch
  // 总条数
  const total = ref(0);
  // 翻译数据
  const translateData = ref([]);
  // 翻译弹窗
  const openViewTranslate = ref(false);
  // 表格状态
  const switchStatus = ref(false);
  // 子表选中数据
  const checkedCategoryDescription = ref([]); // 用于存储已选择的项
  // 类别详情表格数据
  const categoryDescriptionList = ref([]);
  // 类别管理表格数据
  const categoryList = ref([]);
  // 当前页显示的数据
  const tableData = ref([]);
  // 类别管理树选项
  const categoryOptions = ref([]);
  // 弹出层标题
  const title = ref("");
  // 是否显示弹出层
  const open = ref(false);
  // 是否展开，默认全部展开
  const isExpandAll = ref(false);
  // 重新渲染表格状态
  const refreshTable = ref(true);
  // 查询参数
  const queryParamsData = reactive({
    form: {
      status: 1,
    },
    rules: {
      name: [{ required: true, message: "类别名称不能为空", trigger: "blur" }],
      seq: [{ required: true, message: "排序不能为空", trigger: "blur" }],
    },
  });
  const { form, rules } = toRefs(queryParamsData);
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    param: {
      languageId: 1
    },
  });
  // 查看翻译列表
  const viewTranslate = (e) => {
  
    product.productcategory
      .productcategoryGetbyid({
        pathParams: {
          id: e.id,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          console.log("🚀", res.data);
          openViewTranslate.value = true;
          translateData.value = res.data.categoryDescriptionList;
        }
      });
  };
  // 表格状态控制
  const handleStatusChange = (e) => {
    // if(!Judgment.value) return
    console.log(e.status);
    switchStatus.value = true;
    proxy.$modal
      .confirm("确定需要修改此状态吗？")
      .then(() => {
        product.productcategory
          .productcategoryUpdatestatus({
            pathParams: {
              id: e.id,
            },
            params: {
              status: e.status,
            },
          })
          .then((res) => {
            console.log("表格状态控制");
            proxy.$modal.msgSuccess("修改状态成功");
            switchStatus.value = false;
            getList();
          })
          .catch((err) => {
            switchStatus.value = false;
            console.log(err, "[[[[]]]]");
            getList();
          });
      })
      .catch((err) => {
        switchStatus.value = false;
        if (e.status) {
          return (e.status = 0);
        } else {
          return (e.status = 1);
        }
      });
  };
  
  /** 查询类别管理列表 */
  const getList = () => {
    // product.productcategory.productcategoryGetcategories(
  
  
    product.productcategory
      .productcategoryGetcategories({
        data: queryParams.value,
      })
      .then((response) => {
        total.value = response.total;
        tableData.value = response.data;
      });
  };
  
  //分页设置
  const handlePageChange = (newPage) => {
    queryParams.value.pageNum = newPage.page;
    queryParams.value.pageSize = newPage.limit;
    getList();
  };
  
  /** 查询类别管理下拉树结构 */
  const getTreeselect = () => {
    product.productcategory
      .productcategoryGetcategories({
        data: {
          pageNum: 1,
          pageSize: 999,
          param: {
            languageId: 1
          },
        },
      })
      .then((response) => {
        categoryOptions.value = [];
        const data = { id: 0, name: "顶级节点", children: [] };
        categoryOptions.value = response.data
        categoryOptions.value.unshift(data);
      });
  };
  // 取消按钮
  const cancel = () => {
    open.value = false;
    reset();
  };
  // 表单重置
  const reset = () => {
    form.value = {
      fatherId: null,
      seq: 0,
      status: 1,
    };
    categoryDescriptionList.value = [];
    proxy.resetForm("formRef");
  };
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    getList();
  };
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      param: {
        languageId: 1
      },
    };
    handleQuery();
  };
  
  /** 新增按钮操作 */
  const handleAdd = (row) => {
    reset();
    getTreeselect();
    categoryDescriptionList.value = [{ languageId: 1 }];
    if (row != null && row.id) {
      form.value.fatherId = row.id;
    } else {
      form.value.fatherId = 0;
    }
    open.value = true;
    title.value = "新增商品分类";
  };
  /** 展开/折叠操作 */
  const toggleExpandAll = () => {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    proxy.$nextTick(() => {
      refreshTable.value = true;
    });
  };
  const handleUpdate = (row) => {
    /**
     * 修改按钮操作
     * 商品分类管理==》商品分类管理详情
     *  商品类别详情管理==》根据列别id查询类别详情
     */
    product.productcategory
      .productcategoryGetbyid({
        pathParams: {
          id: row.id,
        },
      })
      .then((response) => {
        form.value = response.data;
        product.productcategorydescription
          .productcategorydescriptionGetbyid({
            pathParams: {
              id: row.id,
            },
          })
          .then((listRes) => {
            getTreeselect();
            categoryDescriptionList.value = listRes.data;
            open.value = true;
            title.value = "修改类别管理";
          });
      });
  };
  /** 提交按钮 */
  const submitForm = () => {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {
        console.log(form.value, "提交按钮");
        // return
        form.value.categoryDescriptionList = categoryDescriptionList.value.map(
          (code) => {
            let newItem = { ...code }; // 克隆对象
            delete newItem.id; // 删除 id 属性
            delete newItem.languageName; // 删除 name 属性
            return newItem;
          }
        );
        let newForm = {
          categoryDescriptionList: form.value.categoryDescriptionList,
          fatherId: form.value.fatherId,
          seq: form.value.seq,
          status: form.value.status,
          id: form.value.id,
        };
        if (form.value.id != null) {
          console.log(form.value);
          product.productcategory
            .productcategoryUpdate({
              data: newForm,
            })
            .then((response) => {
              if (response.code === 200) {
                proxy.$modal.msgSuccess("修改成功");
                open.value = false;
                Judgment.value = false; //设置false防止状态status的switch被修改
                getList();
              }
            });
        } else {
          //新增商品分类
          // console.log(form.value);
          product.productcategory
            .productcategoryAdd({
              data: form.value,
            })
            .then((response) => {
              if (response.code === 200) {
                proxy.$modal.msgSuccess("新增成功");
                open.value = false;
                Judgment.value = false; //设置false防止状态status的switch被修改
                getList();
              }
            });
        }
      }
    });
  };
  /** 删除按钮操作 */
  const handleDelete = (rowItem) => {
    proxy.$modal.confirm("是否确认删除此条记录？").then(() => {
      console.log(rowItem);
      return product.productcategory
        .productcategoryDeletebatch({
          data: {
            ids: [rowItem.id],
          },
        })
        .then((res) => {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        });
    });
  };
  
  /** 类别详情添加按钮操作 */
  const handleAddCategoryDescription = () => {
    let obj = {
      languageId: "",
      name: "",
    };
    categoryDescriptionList.value.push(obj);
  };
  /** 类别详情删除按钮操作 */
  const handleDeleteCategoryDescription = () => {
    if (checkedCategoryDescription.value.length == 0) {
      proxy.$modal.msgError("请选择需要删除的语言类型");
    } else {
      categoryDescriptionList.value = categoryDescriptionList.value.filter(
        function (item) {
          return !checkedCategoryDescription.value.includes(item.index);
        }
      );
      checkedCategoryDescription.value = [];
    }
  };
  /** 复选框选中数据 */
  const publicCheck = (selection) => {
    checkedCategoryDescription.value = selection;
  };
  onMounted(() => {
    getList();
  });
  
  const handleTranslationClose = () => {
    openViewTranslate.value = false;
  }
  // 自定义 props
  const treeProps = {
    label: "name",
    value: "id",
    children: "children",
    disabled: (data) => {
      return disableThirdLevel(data);
    },
  };
  const disableThirdLevel = (data) => {
    if (data.status && data.level == 2) {
      return true;
    } else {
      return false;
    }
  };
  </script>
  <style lang="scss" scoped>
  .public_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  </style>
  